package org.dong.Tool;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import java.awt.image.BufferedImage;
import java.io.File;

public class BarcodeGeneratorUtil {
    private static final String OUTPUT_FOLDER = "/static/image/code/"; // 指定的文件夹
    private static final String barcodeType = "CODE_128";

    public static String generateBarcode(ServletContext servletContext, String barcodeData) {
        try {
            // 创建条形码编码器
            MultiFormatWriter barcodeWriter = new MultiFormatWriter();

            // 选择条形码格式
            BarcodeFormat barcodeFormat = BarcodeFormat.valueOf(barcodeType);

            // 生成 BitMatrix（位矩阵）表示的条形码
            BitMatrix bitMatrix = barcodeWriter.encode(barcodeData, barcodeFormat, 400, 200);

            // 将 BitMatrix 转换为 BufferedImage
            BufferedImage barcodeImage = toBufferedImage(bitMatrix);

            // 获取Web应用的实际路径
            String webappRealPath = servletContext.getRealPath("/");

            // 定义输出文件路径和名称
            String outputPath = webappRealPath + OUTPUT_FOLDER + barcodeData + ".png";

            // 创建输出文件对象
            File outputFile = new File(outputPath);

            // 确保输出文件所在的目录存在
            outputFile.getParentFile().mkdirs();

            // 将 BufferedImage 保存为图像文件
            ImageIO.write(barcodeImage, "PNG", outputFile);

            String fileName = outputFile.getName();

            return "static/image/code/"+fileName;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 将 BitMatrix 转换为 BufferedImage
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0x000000 : 0xFFFFFF);
            }
        }
        return image;
    }
}
